from flask import request
from flask_restx import Resource, Namespace, fields
from flask_jwt_extended import create_access_token, get_jwt_identity
from app.utils.auth import token_required
from app.utils.validators import validate_required_fields, validate_username
from app.services.admin_service import AdminService
from . import admin_bp

# 创建认证命名空间，但使用现有蓝图
auth_ns = Namespace('auth', description='认证相关接口')

# 定义请求模型（用于文档生成）
login_request = auth_ns.model('LoginRequest', {
    'username': fields.String(required=True, description='用户名'),
    'password': fields.String(required=True, description='密码')
})

password_request = auth_ns.model('PasswordRequest', {
    'old_password': fields.String(required=True, description='原密码'),
    'new_password': fields.String(required=True, description='新密码')
})

# Flask-RESTX兼容的响应函数
def success_response(data=None, message='操作成功', code=200):
    """成功响应格式 - Flask-RESTX兼容版本"""
    response = {
        'code': code,
        'message': message,
        'data': data
    }
    return response, code

def error_response(message='操作失败', code=400, data=None):
    """错误响应格式 - Flask-RESTX兼容版本"""
    response = {
        'code': code,
        'message': message,
        'data': data
    }
    return response, code

@auth_ns.route('/login')
class LoginAPI(Resource):
    """管理员登录"""
    
    @auth_ns.expect(login_request)
    def post(self):
        # 验证必填字段
        is_valid, error_msg = validate_required_fields(['username', 'password'])
        if not is_valid:
            return error_response(error_msg, 400)
        
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        
        # 验证用户名格式
        if not validate_username(username):
            return error_response('用户名格式不正确', 400)
        
        # 查找管理员
        admin = AdminService.get_by_username(username)
        if not admin:
            return error_response('用户名或密码错误', 400)
        
        # 验证密码
        if not admin.check_password(password):
            return error_response('用户名或密码错误', 400)
        
        # 检查状态
        if not admin.status:
            return error_response('账号已被禁用', 400)
        
        # 生成JWT token（identity必须是字符串）
        access_token = create_access_token(identity=str(admin.id))
        
        # 打印调试信息
        print(f"生成JWT令牌 - 用户名: {username}, ID: {admin.id}")
        
        return success_response({
            'token': access_token,
            'admin_info': admin.to_dict()
        }, '登录成功')


@auth_ns.route('/logout')
class LogoutAPI(Resource):
    """管理员登出"""
    
    @token_required
    def post(self, current_admin):
        return success_response(message='登出成功')


@auth_ns.route('/info')
class InfoAPI(Resource):
    """获取当前管理员信息"""
    
    @token_required
    def get(self, current_admin):
        return success_response(current_admin.to_dict())


@auth_ns.route('/password')
class PasswordAPI(Resource):
    """修改密码"""
    
    @auth_ns.expect(password_request)
    @token_required
    def put(self, current_admin):
        # 验证必填字段
        is_valid, error_msg = validate_required_fields(['old_password', 'new_password'])
        if not is_valid:
            return error_response(error_msg, 400)
        
        data = request.get_json()
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        
        # 验证旧密码
        if not current_admin.check_password(old_password):
            return error_response('原密码不正确', 400)
        
        # 更新密码
        current_admin.set_password(new_password)
        from app import db
        db.session.commit()
        
        return success_response(message='密码修改成功')


# 将命名空间注册到统一的API实例
from . import api
api.add_namespace(auth_ns, path='/auth') 